# MakeBy: LiuBoyuan
import os

from fastapi.encoders import jsonable_encoder

from Config import Config
from Model.GameDetailModel import GameDetailModel
from Schema.GameDetailSchema import NewGame
from Service.Base import BaseService
from Service.UserService import UserLoginService


class GameDetailService(BaseService):
    def __init__(self):
        self.model = GameDetailModel
        self.tablename = "game_detail"

    def newGame(self, newGameSchema: NewGame, sisson):
        """
        添加游戏
        :param newGameSchema:
        :return:sdas
        """

        userLoginService = UserLoginService()
        user = userLoginService.getUserToken(token=newGameSchema.token, session=sisson)
        newGameSchema.token = None

        if user is False:
            return False
        print(f"{jsonable_encoder(user)} - {user.id}")
        newgamemodel = self.model(**newGameSchema.dict())
        newgamemodel.author = user.id

        print(f"[GameDetail] 添加游戏 -> {jsonable_encoder(newgamemodel)}")

        self.add(
            newgamemodel,
            sisson
        )

    async def setGameImage(self, gid, token, image, session):
        print(f"[GameDetail] 设置游戏图片")
        user = UserLoginService().getUserToken(token, session)
        if not user:
            return False
        uid = user.id
        model_game: GameDetailModel = self.getByDict({"game_id": gid}, session)
        filename = token.split(".")[1] + image.filename
        assert len(model_game) > 0
        model_game = model_game[0]
        if model_game.author == uid:
            model_game.game_image = filename
            with open(os.path.join(Config.File.game_head_path, filename), 'wb') as f:
                filebyte = await image.read()
                print(filebyte)
                f.write(filebyte)
            self.update(session, model_game, id_name="game_id")
        else:
            print(f"用户不同{uid}不是{model_game.author}")

gameDetailService = GameDetailService()
